package org.opfx.tools.ant.php.util;

import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Execute;

public class PHP extends Execute {

	private static final String PROPERTY_NAME_PHP_EXEC = "php.exec";
	private static final String PROPERTY_NAME_PHP_ROOT_DIR = "php.exec.dir";
	private static final String PROPERTY_NAME_PHP_PEAR_DIR = "php.pear.dir";
	

	static private PHP instance;
	private Project project;
	private String pathRoot;
	private String pathPear;
	private String phpExec;
	
	private PHP(Project project) {

		super();
		this.setProject(project);
	}	

	static public PHP getInstance(Project project) {
		if (instance == null) {
			instance = new PHP(project);
		}
		return instance;
	}
	
	private void setProject(Project project) {
		this.project = project;
		
		@SuppressWarnings("rawtypes")
		Hashtable props = project.getProperties();
		phpExec = (String) props.get("php.exec");
		
		
	}

	public void lint(File sourceFile) throws BuildException {
		
		if (phpExec==null) {
			return;
		}
		 try {
			File emptyPhpIni = File.createTempFile("php", "ini");
			
	
			 String [] cmds;
			 cmds = new String[4];
			 cmds[0] = phpExec;
			 cmds[1] = "-c " + emptyPhpIni.getAbsolutePath();
			 cmds[2] = "-l";
			 cmds[3] = sourceFile.getAbsolutePath();

			 setCommandline(cmds);
			 
			 int exitCode = execute();
			 
			 if(exitCode==-1) {
				 throw new BuildException();
			 }
		
//			 if( execute() == -1) {
//			 	throw new BuildException();
//			 }	
			 	
			 
			 emptyPhpIni.delete();
		 }catch(IOException ioe) {
			 
		 }finally{
			
		 }
		 
	}

	public void log(String msg, int msgLevel) {
		if (project != null) {
			project.log(msg, msgLevel);
		}
	}

}
